import * as types from '../actions/actionTypes';

const initialState = {
  tags : [],
  files: []
}

function clone(o){
    var k, ret= o, b;
    if(o && ((b = (o instanceof Array)) || o instanceof Object)) {
        ret = b ? [] : {};
        for(k in o){
            if(o.hasOwnProperty(k)){
                ret[k] = clone(o[k]);
            }
        }
    }
    return ret;
}

export default function(state = initialState,action) {
    switch (action.type){
        case types.FetchTagSuccess:{
            return {...state,
                      tags:action.tags
                    }

        }
        case types.AddTag:{
          var tags = clone(state.tags);
          tags.push(action.tag);
            return {...state,
                      tags:tags
                    }
        }
        case types.FetchFileByTag:{
            return {...state,
                      files:action.files
                    }
        }
        case types.RemoveTag:{
          let tags = clone(state.tags);
          for(let i = 0;i < tags.length;i++){
            if(tags[i] == action.tag){
              tags.splice(i,1)
            }
          }
            return {...state,
                      tags:tags
                    }
        }

    }
    return state;
}
